package com.example.community.rest;

import com.example.community.dto.UpdateUserDto;
import com.example.community.dto.UserDto;
import com.example.community.mapper.UserMapper;
import com.example.community.model.User;
import com.example.community.model.UserExample;
import com.example.community.service.UserService;
import com.example.community.util.CookieChecking;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
public class UserResource {
    @Autowired
    UserService userService;


    @PostMapping("/updateMessage")
    public Map<String,String> updateMessage(@RequestBody UserDto userDto, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String token = CookieChecking.CookieToken(cookies,"token");
        Map<String,String> map = new HashMap<>();
        if (token != null){
            if (token.startsWith("UR")){
                String userToken = token.substring(2);
                Long id = userService.getUserId(userToken);
                User user = new User();
                user.setName(userDto.getName());
                user.setBio(userDto.getBio());
                user.setPicUrl(userDto.getAvatarUrl());
                userService.updateUser(user,id);
                map.put("message","success");
                return map;
            }else {
                map.put("message","error");
                return map;
            }
        }
        map.put("message","error");
        return map;
    }
}
